<?php

namespace App\Models;

use App\User;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Follow extends Model
{
    protected $table = 'c_follows';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 属于哪个工作室
     */
    public function work()
    {
        return $this->belongsTo('App\Models\DoctorWorks', 'work_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 属于那个医生
     */
    public function doctor()
    {
        return $this->belongsTo('App\Models\Doctor', 'work_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     * 属于哪里个用户
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    /****
     * @param $filter
     * @return int
     * 收藏或取消
     */
    public function setWorkFollow($filter)
    {
        $info = $this->getInfos($filter);
        if (!empty($info)) { //取消收藏
            $foll_info = $this->where("work_id", '=', $filter['work_id'])
                ->where("user_id", '=', $filter['user_id'])
                ->where('type', '=', $filter['type'])->first();
                if($filter['type'] ==1){
                    (new DoctorWorks())->where([['id', '=', $filter['work_id']]])->decrement("fans_num");
//                    删除病例
                    $book = (new AddressBook())->where([['case_id','=',$foll_info->case_id],['work_id','=',$filter['work_id']],['user_id','=',$filter['user_id']]])->first();
                    if($book){
                        (new AddressBook())->where([['case_id','=',$foll_info->case_id],['work_id','=',$filter['work_id']],['user_id','=',$filter['user_id']]])->delete();
                        (new AddressBookRelateLabel())->where([['address_book_id','=',$book->id],['work_id','=',$filter['work_id']]])->delete();
                        $vvs = TaskHall::where(['id'=>9])->value("growup_num");
                        $growth_value = DoctorWorks::where(['id'=>$filter['work_id']])->value("growth_value");
                        if($growth_value  >= $vvs){
                            DoctorWorks::where(['id'=>$filter['work_id']])->decrement("growth_value",$vvs);
                        }
                    }
                    $this->where("work_id", '=', $filter['work_id'])
                        ->where("user_id", '=', $filter['user_id'])
                        ->where('type', '=', $filter['type'])->delete();
                }else{
                    $this->where("work_id", '=', $filter['work_id'])
                        ->where("user_id", '=', $filter['user_id'])
                        ->where('type', '=', $filter['type'])->delete();
                    (new Doctor())->where([['id', '=', $filter['work_id']]])->decrement("fans_num");
                }
                return 1;

        } else {
            $this->work_id = $filter['work_id'];
            $this->user_id = $filter['user_id'];
            $this->type = $filter['type'];
            $this->case_id = isset($filter['case_id'])?$filter['case_id']:0;
            //查询是否有病历夹
            $caseinfo = (new CaseDescribe())->where([['id','=',$filter['case_id']]])->first();
            if(empty($caseinfo)){
                return 5;
            }
            $res = $this->save();
            if ($res) {
                if($filter['type'] ==1){
                    (new DoctorWorks())->where([['id', '=', $filter['work_id']]])->increment("fans_num");
                    $cs["work_id"] = $filter['work_id'];
                }else{
                    (new Doctor())->where([['id', '=', $filter['work_id']]])->increment("fans_num");
                    $cs["work_id"] = (new Doctor())->where([['id','=',$filter['work_id']]])->value("work_id");
                    return 3;
                }
                $add_book = (new AddressBook())->where([["case_id",'=',$caseinfo->id],['user_id','=',$filter['user_id']],['work_id','=',$filter['work_id']]])->first();
                if($add_book){
                    return 3;
                }
                $user_info =  (new User())->where([['id','=',$filter['user_id']]])->first();
                $cs["user_name"] = $caseinfo->name;
                $cs["sex"] = $caseinfo->sex;
                $cs["age"] = $caseinfo->age;
                $cs["type"] = 1;
                $cs["image"] = !empty($caseinfo->picture[0])?json_encode($caseinfo->picture):json_encode([]);
                $cs["describe"] = isset($caseinfo->describe)?$caseinfo->describe:"";
                $cs["phone"] = $user_info->phone;
                $cs["user_id"] = $caseinfo->user_id;
                $cs["case_id"] = $caseinfo->id;
                $last = (new OrderGoods())
                    ->where([['user_id','=',$filter['user_id']],['work_id','=',$filter['work_id']],['specs_id','=',$caseinfo->id]])->orderBy("id","desc")->first();
                if($last){
                    $o = (new Order())->where([['id','=',]])->first();
                    if($o){
                        $cs["last_chat_time"] = $o->consult_time;
                    }
                }
                $cs["created_at"] = date("Y-m-d H:i:s",time());
                $cs["updated_at"] = date("Y-m-d H:i:s",time());
                $b_info = DB::table("c_address_books")->where([['type','=',1],['user_id','=',$caseinfo->user_id],['case_id','=',$caseinfo->id],['work_id','=',$cs["work_id"]]])->first();
                if(empty($b_info)){
                    $book_id = DB::table("c_address_books")->insertGetId($cs);
                    //通讯录增加一个用户加成长值
                    GrowthNumberLog::add(["work_id"=>$cs["work_id"]],9);
                }else{
                    $book_id = $b_info->id;
                }
                $tl['address_book_id'] = $book_id;
                $tl['address_book_label_id'] = (new AddressBookLabel())->where([['is_default','=',1],['num','=',1],["work_id",'=',$filter['work_id']]])->value('id');
                $tl['work_id'] = $filter['work_id'];
                $tl['created_at'] = date("Y-m-d H:i:s",time());
                $tl['updated_at'] = date("Y-m-d H:i:s",time());
                $ha = DB::table("c_address_book_relate_labels")->where([['address_book_id','=', $tl['address_book_id']],['address_book_label_id','=',$tl['address_book_label_id']],['work_id','=', $tl['work_id']]])->first();
                if(empty($ha)){
                    DB::table("c_address_book_relate_labels")->insertGetId($tl);
                }
                return 3;
            } else {
                return 4;
            }
        }
    }

    //详情
    public function getInfos($data)
    {
        return $this->where("work_id", '=', $data['work_id'])
            ->where("user_id", '=', $data['user_id'])
            ->where('type', '=', $data['type'])
            ->first();
    }

    /***
     * 获取关注列表
     */
    public function getFollowList($filter)
    {
        if ($filter['type'] == 1) { //医护室
            $with = ['work'];
        } elseif ($filter['type'] == 2) { //医师
            $with = ['doctor'];
        }
        $limit = isset($filter['limit']) ?: 150;
        $res = $this->with($with)
            ->where("user_id", '=', $filter['user_id'])
            ->where('type', '=', $filter['type'])
            ->orderByDesc("id")
            ->simplePaginate($limit);
        if ($filter['type'] == 1) { //医护室
            if (!empty($res)) {
                $res = $res->toArray();
                $host = new Url();
                $cli_name = new ClinicCategory();
                foreach ($res['data'] as $k => $v) {
                    if (!empty($v['work'])) {
                        $res['data'][$k]['work']['distance'] = $this->calculateDistance($filter['lat'], $filter['lng'], $v['work']['lat'], $v['work']['lng']);
                        $res['data'][$k]['work']['logo'] = $host::getHttpHost() . 'upload/' . $v['work']['logo'];
                        $res['data'][$k]['work']['clinic_name'] = $cli_name->where([['id', '=', $v['work']['clinic_id']]])->value("classify_name");
                    }else{
                        unset($res['data'][$k]);
                        //删除关注记录
                        $this::destroy($v['id']);
                    }
                }
                return $res;
            }
        }
        if (!empty($res)) {
            return $res->toArray();
        }
        return [];
    }

    public function calculateDistance($lat1, $lon1, $lat2, $lon2)
    {
        $earthRadius = 6371; // 地球半径，单位为千米
        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);
        $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $distance = $earthRadius * $c;
        return number_format($distance, 2);
    }
}
